package org.exhibition.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.exhibition.domain.pojo.exhibition.UserTicketOrder;
import org.exhibition.mapper.ExhibitionMapper;
import org.exhibition.service.ExhibitionOrderService;
import org.museum.api.client.IdentityBackendClient;
import org.museum.api.client.IdentityNameClient;
import org.museum.api.domain.IdentityName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Slf4j
public class ExhibitionOrderServiceImpl implements ExhibitionOrderService {
    @Autowired
    private ExhibitionMapper exhibitionMapper;
    @Autowired
    private IdentityNameClient identityNameClient;
    @Autowired
    private IdentityBackendClient identityBackendClient;


    @Override
    @Transactional
    public String executeOrderTransaction(UserTicketOrder userTicketOrder){
        System.out.println("开始库存扣减操作和订单写入");
        log.debug("开始库存扣减操作和订单写入");
        if (exhibitionMapper.updateExhibitionTicket(userTicketOrder.getTicketId()) > 0) {
            try {
                log.debug("哈哈哈{}", userTicketOrder);
                System.out.println("开始添加用户信息");
                identityNameClient.addIdentityByName(new IdentityName(userTicketOrder.getIdentity(),userTicketOrder.getName()));
                identityBackendClient.addIdentityName(new IdentityName(userTicketOrder.getIdentity(),userTicketOrder.getName()));
                log.debug("添加用户信息成功");
                System.out.println("开始添加订单信息");
                System.out.println(userTicketOrder);
                exhibitionMapper.submitExhibitionReservation(userTicketOrder);
                System.out.println("添加订单信息成功");
                return "预购成功";
            } catch (DuplicateKeyException e) {
                System.out.println(e);
                System.out.println("该用户已购买");
                // 数据库唯一约束兜底
                return "该用户已购买";
            }
        } else {
            System.out.println("票已经售罄");
            log.debug("该票已售完");
            return "该票已售完";
        }
    }
}
